import { initializationMapMgr } from '../coreFunctions/initializationMap.ts'
import { controlMgr } from '../tool/control.ts'
import { showErrorMessage } from "../message/index";
import { rander } from '../coreFunctions/rander.ts'
import { cameraManager } from "../coreFunctions/cameraManager.ts";
import { startModelMovement, removeModelAndTrack } from "../coreFunctions/modelMoveManager.ts";
import { realTimeMobile } from "../coreFunctions/modelMoveManager copy.ts";
import { layersManager } from '../coreFunctions/layerManager.ts';
import { playback } from '../coreFunctions/playback.ts';
import { defaultCoordinates } from "../config/ip.ts";
import { ClusterLayerManager } from "../coreFunctions/ClusterLayerManager.ts";
import { ClusterLayerManagers } from "../coreFunctions/ClusterLayerManager copy.ts";
import { popupManager } from "../coreFunctions/popupManager.ts";
import { getAssets } from "@/utils";
import { popupNotification } from '../config/mapStyles';

let map: any = null
export const mapApi = {
    map: {
        //  初始化地图
        initMap(containerId: string, mapOptions: any) {
            try {
                map = initializationMapMgr.initializationMap(containerId, mapOptions)
                return map
            } catch (error) {
                showErrorMessage(error + '')
            }

        },
        // 切换图层
        changeMapLayer(mapType: string) {
            try {
                initializationMapMgr.changeMapStyle(map, mapType)
            }
            catch (error) {
                showErrorMessage(error + '')
            }

        },
        // 改变2D/3D地图
        changeMapType(mapType: string) {
            try {
                initializationMapMgr.changeMapMode(map, mapType)
            }
            catch (error) {
                showErrorMessage(error + '')
            }
        },
        //  获取地图对象
        getMap() {
            return map
        }
    },
    control: {
        // 全屏控件
        screenControl(map: any) {
            try {
                controlMgr.screenControl(map)
            } catch (error) {
                showErrorMessage(error + '')
            }

        },
        //  比例尺控件
        scaleControl(map: any) {
            try {
                controlMgr.scaleControl(map)
            } catch (error) {
                showErrorMessage(error + '')
            }

        },
        //  导航控件
        navControl(map: any) {
            try {
                controlMgr.navControl(map)
            } catch (error) {
                showErrorMessage(error + '')
            }

        },
        //  移除控件  
        removeControl(map: any, control: any) {
            try {
                controlMgr.removeControl(map, control)
            }
            catch (error) {
                showErrorMessage(error + '')
            }

        }
    },
    rander: {
        //  渲染边界线
        loadBoundaryLine(id: string, data: any) {
            try {
                rander.boundManager.boundaryLine(map, id, data)
            }
            catch (error) {
                showErrorMessage(error + '')
                console.error(error)
            }

        },
        //  渲染注记
        loadBoundaryLabel(id: string, data: any) {
            try {
                rander.boundManager.boundaryLabel(map, id, data)
            }
            catch (error) {
                showErrorMessage(error + '')
                console.error(error)
            }
        },
        // 加载聚合
        loadCluster() {
            // images [] , data{},
            // 定义图标配置
            let data = []
            for (let i = 0; i < 100; i++) {
                data.push({
                    id: i,
                    name: i, // 标记点名称
                    coordinates: [110 + Math.random() * 10, 30 + Math.random() * 10], // 标记点坐标;
                    data: {
                        type: 1 + Math.floor(Math.random() * 5),
                        label: "测试" + i
                    } // 可选的数据属性，用于存储与标记点相关的额外信息
                })
            }
            const image = [{
                id: 'position',
                url: getAssets(`images/model/position-removebg-preview.png`)
            },
            {
                id: 'defaultIcon',
                url: getAssets(`images/logo/logo.png`)
            }]
            let geojson = {
                type: "FeatureCollection",
                features: [],
            };

            for (let i = 0; i < data.length - 1; i++) {
                geojson.features.push({
                    type: "Feature",
                    properties: {
                        ...data[i].data,
                    },
                    geometry: {
                        type: "Point",
                        coordinates: data[i].coordinates,
                    },
                });
            }

            // 加载聚合图标
            ClusterLayerManagers.loadClusterImages(map, image)

            // 加载聚合资源
            ClusterLayerManagers.loadClusterSource(map, 'cluster', geojson)


            // 监听点击事件
            map.on('click', (e) => {
                // 获取点击位置的元素
                const features = map.queryRenderedFeatures(e.point);
                if (features.length > 0) {
                    const properties = features[features.length - 1].properties;
                    const coordinates = features[features.length - 1].geometry.coordinates;
                    let popup = popupManager.getPopupById("cluster_popup");
                    // 如果popup不存在，创建popup
                    if (!popup) {
                        // 如果 popup 不存在，创建 popup
                        popup = popupManager.createPopup(map, "cluster_popup", coordinates, popupNotification.clusterLayer(properties));
                    }

                    popupManager.updatePopupPositition("cluster_popup", coordinates);
                    popupManager.updatePopup(popup, popupNotification.clusterLayer(properties))
                }


            });

            // 鼠标悬停时显示指针
            map.on('mouseenter', () => {
                map.getCanvas().style.cursor = 'pointer';
            });

            // 鼠标离开时恢复默认指针
            map.on('mouseleave', () => {
                map.getCanvas().style.cursor = '';
            });
            // popupManager.createPopup(map, "cluster_popup", [0, 0], `<div>123</div>`);

            // setTimeout(() => {
            //     ClusterLayerManagers.removeClusterLayer(map, 'cluster')
            //     ClusterLayerManagers.removeClusterSource(map, 'cluster')


            // }, 10000);
            // setTimeout(() => {
            //     ClusterLayerManagers.removeClusterLayer(map, 'clusterLayerName')
            //     ClusterLayerManagers.removeClusterSource(map, 'clusterSourceName')
            // }, 5000);
            // console.log( getAssets(`images/logo/logo.png`));

            // const data = [
            //     { type: 'icon-1', coordinates: [-74.5, 40.1], label: 'Poin1' },
            //     { type: 'icon-1', coordinates: [-74.6, 40.2], label: 'Point2' },
            //     // 更多点数据...
            // ];
            // const clusterLayer = new ClusterLayerManager(map, data, icons)
            // clusterLayer.initialize();
        },
        // 添加一个geojson数据
        loadGeoJson(data: Array<any>) {
                
        }

    },
    camera: {
        //  飞到指定位置
        flyTo(coordinate: [number, number], options?: any) {
            cameraManager.flyToCenter(map, coordinate, options)
        },
        // 回到初始位置
        flyToInit() {
            cameraManager.flyToCenter(map, defaultCoordinates, { zoom: 4.5 })
        },
        // 放大级别
        zoomIn() {
            // 获取相机信息
            const cameraInfo = cameraManager.getCamera(map)
            cameraManager.setZoom(map, Number(cameraInfo.zoom + 0.5))
        },
        // 缩小级别
        zoomOut() {
            // 获取相机信息
            const cameraInfo = cameraManager.getCamera(map)
            cameraManager.setZoom(map, Number(cameraInfo.zoom - 0.5))
        }
    },
    modelMove: {
        // 加载飞机模型
        realTimeLoadModel(data: Array<any>) {

            try {
                // modelMoveManager.initModelManager(map, data)
            }
            catch (error) {
                showErrorMessage(error + '')
                console.error(error)
            }
        },
        // 移动飞机模型  ,  实时移动
        realTImeMoveModel(id: string, coordinate: [number, number, number]) {
            try {
                // this.realTimeToggleModel(id) // 控制飞机模型是否显示
                // 移动飞机模型
                startModelMovement(map, id, coordinate)
            }
            catch (error) {
                showErrorMessage(error + '')
                console.error(error)
            }
        },
        newReal() {
            realTimeMobile.loadPlaneImage(map, [{
                id: 'plane',
                url: getAssets(`images/model/feiji.png`)
            }])


            // 示例：动态加载飞机并更新位置
            setInterval(() => {
                // console.log([-77.0369 + Math.random(), 38.9072 + Math.random()]);

                realTimeMobile.updatePlanePosition(map, 'plane', [-77.0369 + Math.random() + 1, 38.9072 + Math.random() + 1]);
                // realTimeMobile.updatePlanePosition(map, 'plane', [-72.0369 + Math.random() + 1, 38.9072 + Math.random() + 1]);
            }, 1000);

            // setTimeout(() => {
            //     realTimeMobile.updatePlanePosition(map,'plane', [-77.035, 38.908]);
            // }, 3000);
        },
        // 控制飞机模型是否显示，  实时移动
        realTimeToggleModel(id: string) {
            const isVisible = layersManager.getVisible(map, id)
            if (isVisible == 'none') {
                layersManager.toggleLayerVisibility(map, id)
                // layersManager.toggleLayerVisibility(map, id + "_line")
            }
        },
        // 移除飞机模型 实时
        removeRealModel(id: string) {
            removeModelAndTrack(map, id)
        },
        // 加载回放模型   ,  回放移动
        callPlayBackLoadModell(czml: any) {
            playback.loadfModelTracks(map, czml)
        },
        // 移动回放模型
        callPlayBackMoveModel(currentTime: number) {
            console.log(currentTime);

            playback.moveModel(currentTime)
        },
        // 移除飞机模型  回放
        removeCallPlayBackModel(id: string) {
            console.log(id);

            playback.remove(map, id)
        }
    },
    layer: {
        // 移除图层
        removeLayer(id: string) {
            try {
                layersManager.removeLayer(map, id)
            }
            catch (error) {
                showErrorMessage(error + '')
                console.error(error)
            }
        },
        // 控制图层是否显示
        toggleLayerVisibility(id: string) {
            try {
                layersManager.toggleLayerVisibility(map, id)
            }
            catch (error) {
                showErrorMessage(error + '')
                console.error(error)
            }
        }
    }

}